<template>
  <div class="rule-edit">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>流程管理</el-breadcrumb-item>
      <el-breadcrumb-item
        ><a href="/#/systemtools/processManagePlatform/rule"
          >流程规则</a
        ></el-breadcrumb-item
      >
      <el-breadcrumb-item
        ><a>{{ ifEdit ? "编辑" : "查看" }}</a></el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="edit-content">
      <el-table :data="ruleDetail" border>
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="流程节点" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.process_node"
              placeholder="请选择流程节点"
              :disabled="scope.$index === 0 || scope.$index === 1 || !ifEdit"
              size="mini"
              @change="changePorcessNode(scope.row)"
            >
              <el-option
                v-for="item in nodeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="
                  item.disabled ||
                  (item.value === 'end' &&
                    scope.$index !== ruleDetail.length - 1)
                "
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="按钮设置" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.buttons_set"
              size="mini"
              multiple
              collapse-tags
              placeholder="请选择"
              :disabled="!buttons_set[scope.row.process_node] || !ifEdit"
            >
              <el-option
                v-for="item in buttons_set[scope.row.process_node]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="任务模式" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.task_mode"
              placeholder="请选择任务模式"
              :disabled="scope.row.process_node !== 'task' || !ifEdit"
              size="mini"
            >
              <el-option
                v-for="item in task_modes"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
            <el-tooltip
              class="item"
              effect="dark"
              content="人员设置"
              placement="top"
              v-if="scope.row.task_mode && ifEdit"
            >
              <i
                class="el-icon-setting"
                @click="toPersonSet(scope.$index, scope.row.personSetForm)"
              ></i>
            </el-tooltip>
            <i v-else class="el-icon-setting disable"></i>
          </template>
        </el-table-column>
        <template slot="append">
          <div class="append-row">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addRow"
              :disabled="
                ruleDetail.filter((item) => item.process_node === 'end')
                  .length === 1 || !ifEdit
              "
              >新增一行</el-button
            >
            <el-button
              :disabled="ruleDetail.length <= 2 || !ifEdit"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRow"
              >删除一行</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="save(1)"
              :disabled="!ifEdit"
              >发布</el-button
            >
            <el-button size="mini" @click="save(0)" :disabled="!ifEdit"
              >保存</el-button
            >
          </div>
        </template>
      </el-table>
    </div>
    <el-dialog
      title="人员设置"
      :visible.sync="personSetVisible"
      width="30%"
      @open="personSetFormOpen"
    >
      <el-form :model="personSetForm" ref="personSetForm">
        <el-form-item
          label="模式"
          label-width="80px"
          :rules="[{ required: true, message: '请选择模式' }]"
          prop="mode"
        >
          <el-select v-model="personSetForm.mode" placeholder="请选择">
            <el-option
              v-for="item in personSetModes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="选择人员"
          v-if="personSetForm.mode === 'targetPerson'"
          label-width="80px"
          :rules="[{ required: true, message: '请选择人员', trigger: 'blur' }]"
          prop="personSelected"
        >
          <person-search v-model="personSetForm.personSelected" />
        </el-form-item>
        <el-form-item
          label="选择部门"
          v-if="
            personSetForm.mode === 'departmentHead' ||
            personSetForm.mode === 'targetDepart'
          "
          label-width="80px"
          prop="departSelected"
          :rules="[
            { required: true, message: '请选择部门', trigger: 'change' },
          ]"
        >
          <el-input
            v-if="personSetForm.departSelected"
            v-model="personSetForm.departSelected.dept_name"
            disabled
          ></el-input>
          <tree-search
            @changeDialogVisible="changeDialogVisible"
            @dialogSubmit="dialogSubmit"
            :dialogVisible="treeDialogVisible"
            :ifSingle="true"
            :selected_dept="
              personSetForm.departSelected
                ? [personSetForm.departSelected]
                : null
            "
          >
            <el-button
              type="text"
              icon="el-icon-plus"
              @click="treeDialogVisible = true"
              slot="title"
              >{{ personSetForm.departSelected ? "更换" : "添加" }}</el-button
            >
          </tree-search>
        </el-form-item>
        <el-form-item
          label="配置"
          label-width="80px"
          v-if="personSetForm.mode === 'lineUp'"
          required
          prop="line_up"
          :rules="[
            {
              required: true,
              validator: lineUpValidator,
            },
          ]"
        >
          <div class="inputs">
            <el-input-number
              size="mini"
              v-model="personSetForm.line_up[0]"
              :min="1"
              :max="8"
              label="开始"
            ></el-input-number
            >~
            <el-input-number
              size="mini"
              v-model="personSetForm.line_up[1]"
              :min="1"
              :max="8"
              label="开始"
            ></el-input-number>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="personSetVisible = false">取 消</el-button>
        <el-button type="primary" @click="personSetSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import personSearch from "@/components/public/personSearch.vue";
import TreeSearch from "@/components/public/treeSearch.vue";
import {
  getProcessRuleContent,
  saveProcessRuleContent,
  updateProcessRuleContent,
} from "@/http/api";
export default {
  components: { personSearch, TreeSearch },
  name: "ruleEdit",
  data() {
    return {
      ruleDetail: [],
      nodeOptions: [
        {
          label: "开始",
          value: "start",
          disabled: true,
        },
        {
          label: "提交节点",
          value: "submit",
          disabled: true,
        },
        {
          label: "任务节点",
          value: "task",
          disabled: false,
        },
        {
          label: "结束",
          value: "end",
          disabled: false,
        },
      ],
      buttons_set: {
        submit: [
          {
            label: "提交",
            value: "submit",
          },
          {
            label: "撤回",
            value: "recall",
          },
        ],
        task: [
          {
            label: "同意",
            value: "agree",
          },
          {
            label: "拒绝",
            value: "refuse",
          },
          {
            label: "知会",
            value: "tell",
          },
        ],
      },
      task_modes: [
        {
          label: "竞签",
          value: "compete",
        },
        {
          label: "并签",
          value: "parallel",
        },
        {
          label: "串签",
          value: "order",
        },
      ],
      personSetVisible: false,
      personSetForm: {
        mode: "",
        personSelected: "",
        departSelected: "",
        line_up: ["", ""],
      },
      personSetModes: [
        {
          label: "指定人员",
          value: "targetPerson",
        },
        {
          label: "直线上级",
          value: "lineUp",
        },
        {
          label: "部门负责人",
          value: "departmentHead",
        },
        {
          label: "指定部门",
          value: "targetDepart",
        },
      ],
      treeDialogVisible: false,
      nowIndex: -1,
      process_rule_code: "",
      ifEdit: false,
      addOrEdit: "add",
    };
  },
  mounted() {
    if (this.$route.params.process_rule_code !== undefined) {
      this.process_rule_code = this.$route.params.process_rule_code;
      sessionStorage.setItem(
        "process_rule_code",
        this.$route.params.process_rule_code
      );
      this.ifEdit = this.$route.params.ifEdit;
      sessionStorage.setItem("ifEdit", this.$route.params.ifEdit);
    } else {
      this.process_rule_code = sessionStorage.getItem("process_rule_code");
      this.ifEdit = sessionStorage.getItem("ifEdit");
    }
    this.getList();
  },
  methods: {
    addRow() {
      this.ruleDetail.push({
        process_node: "",
        buttons_set: [],
        task_mode: "",
        personSetForm: {
          mode: "",
          personSelected: "",
          departSelected: "",
          line_up: ["", ""],
        },
      });
    },
    deleteRow() {
      this.ruleDetail.pop();
      if (
        this.ruleDetail.filter((item) => item.process_node === "end").length
      ) {
        this.nodeOptions[3].disabled = true;
      } else {
        this.nodeOptions[3].disabled = false;
      }
    },
    changePorcessNode(row) {
      if (
        this.ruleDetail.filter((item) => item.process_node === "end").length
      ) {
        this.nodeOptions[3].disabled = true;
      } else {
        this.nodeOptions[3].disabled = false;
      }
      if (row.process_node === "task") {
        row.buttons_set.push("agree", "refuse");
      } else if (row.process_node === "end") {
        row.buttons_set = [];
        row.task_mode = "";
      }
    },
    changeDialogVisible(visible) {
      this.treeDialogVisible = visible;
    },
    dialogSubmit(selectedNodes) {
      this.personSetForm.departSelected = selectedNodes;
      this.treeDialogVisible = false;
    },
    personSetSubmit() {
      this.$refs.personSetForm.validate((res) => {
        if (res) {
          for (const key in this.personSetForm) {
            if (this.personSetForm[key]) {
              this.ruleDetail[this.nowIndex].personSetForm[key] =
                this.personSetForm[key];
            }
          }
          this.personSetVisible = false;
        }
      });
    },
    lineUpValidator(_, value, callback) {
      if (!(value[0] && value[1])) {
        callback(new Error("请进行配置"));
      } else {
        value[0] <= value[1] ? callback() : callback(new Error("配置错误"));
      }
    },
    toPersonSet(index, personSetForm) {
      this.nowIndex = index;
      for (const key in personSetForm) {
        this.personSetForm[key] = personSetForm[key];
      }
      this.personSetVisible = true;
    },
    personSetFormOpen() {
      setTimeout(() => {
        this.$refs.personSetForm.clearValidate();
      });
      this.personSetVisible = true;
    },
    async save(type) {
      let data = JSON.parse(JSON.stringify(this.ruleDetail));
      data.forEach((item) => {
        if (item.process_node === "task") {
          item.select_mode = item.personSetForm.mode;
          if (item.select_mode) {
            if (item.personSetForm.mode === "targetPerson") {
              item.setting = item.personSetForm.personSelected.employee_id;
            } else if (item.personSetForm.mode === "lineUp") {
              item.setting = `${item.personSetForm.line_up[0]},${item.personSetForm.line_up[1]}`;
            } else {
              item.setting = item.personSetForm.departSelected[0]
                ? item.personSetForm.departSelected[0].dept_id
                : item.personSetForm.departSelected.dept_id;
            }
          }
        }
        item.personSetForm = undefined;
      });
      let ifCanSubmit = true;
      for (let i = 0; i < data.length; i++) {
        if (data[i].process_node === "") {
          this.$message.error(`Line${i + 1} 请选择流程节点`);
          ifCanSubmit = false;
          break;
        }
        if (
          (data[i].process_node === "submit" ||
            data[i].process_node === "task") &&
          data[i].buttons_set.length === 0
        ) {
          this.$message.error(`Line${i + 1} 请设置按钮`);
          ifCanSubmit = false;
          break;
        }
        if (data[i].process_node === "task") {
          if (data[i].task_mode === "") {
            this.$message.error(`Line${i + 1} 请选择任务模式`);
            ifCanSubmit = false;
            break;
          }
          if (data[i].select_mode === "") {
            this.$message.error(`Line${i + 1} 请设置人员选择模式`);
            ifCanSubmit = false;
            break;
          }
        }
      }
      if (!ifCanSubmit) {
        return;
      }
      if (
        !this.ruleDetail.filter((item) => item.process_node === "task").length
      ) {
        this.$message.error("Line center 请设置任务节点");
        return;
      }
      if (
        !this.ruleDetail.filter((item) => item.process_node === "end").length
      ) {
        this.$message.error("Line end 请设置结束节点");
        return;
      }
      data = data.filter((item) => {
        return item.process_node === "submit" || item.process_node === "task";
      });
      data.forEach((item) => {
        item.process_rule_code = this.process_rule_code;
      });
      let newData = {
        data,
        status: type,
      };
      let res = {};
      if (this.addOrEdit === "add") {
        res = await saveProcessRuleContent(newData);
      } else {
        res = await updateProcessRuleContent(newData);
      }
      if (res.code === 20011 || res.code === 20031) {
        this.$message.success("保存成功");
      } else {
        this.$message.error(res.msg);
      }
    },
    async getList() {
      let res = await getProcessRuleContent(this.process_rule_code);
      if (res.code === 20041) {
        if (!res.data.length) {
          this.addOrEdit = "add";
          this.ruleDetail = [
            {
              process_node: "start",
              buttons_set: [],
              task_mode: "",
              personSetForm: {
                mode: "",
                personSelected: {},
                departSelected: "",
                line_up: ["", ""],
              },
            },
            {
              process_node: "submit",
              buttons_set: ["submit"],
              task_mode: "",
              personSetForm: {
                mode: "",
                personSelected: {},
                departSelected: "",
                line_up: ["", ""],
              },
            },
          ];
        } else {
          this.addOrEdit = "edit";
          res.data.forEach((item) => {
            item.personSetForm = {
              mode: item.select_mode,
              personSelected: item.target_person,
              departSelected: item.target_dept,
              line_up: item.line_up ?? ["", ""],
            };
          });
          this.ruleDetail = [
            {
              process_node: "start",
              buttons_set: [],
              task_mode: "",
              personSetForm: {
                mode: "",
                personSelected: {},
                departSelected: "",
                line_up: ["", ""],
              },
            },
            ...res.data,
            {
              process_node: "end",
              buttons_set: [],
              task_mode: "",
              personSetForm: {
                mode: "",
                personSelected: {},
                departSelected: "",
                line_up: ["", ""],
              },
            },
          ];
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
.rule-edit {
  /deep/ .append-row {
    width: 100%;
    line-height: 40px;
    height: 40px;
    text-align: center;
    cursor: pointer;
    &:hover {
      background-color: #f5f7fa;
    }
    .el-icon-plus {
      padding-right: 4px;
    }
  }
  /deep/ .edit-content {
    .el-icon-setting {
      padding-left: 6px;
      cursor: pointer;
      &.disable {
        color: #ccc;
        cursor: default;
      }
    }
  }
  /deep/ .inputs {
    display: flex;
    align-items: center;
  }
}
</style>
